﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBlog.IService;
using MyBlog.Model;
using MyBlog.WebApi.Utility.ApiResult;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyBlog.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TypeController : ControllerBase
    {
        private readonly ITypeInfoService _iTypeInfoService;
        public TypeController(ITypeInfoService iTypeInfoService)
        {
            this._iTypeInfoService = iTypeInfoService;
        }

       /// <summary>
       /// 获取所有类型
       /// </summary>
       /// <returns></returns>
        [HttpGet("GetTypes")]
        public async Task<ApiResult> GetTypes()
        {
            var types = await _iTypeInfoService.QueryAsync();
            if (types.Count == 0) return ApiResultHelper.Error("没有更多的类型");
            return ApiResultHelper.Success(types);
        }

        /// <summary>
        /// 创建类型
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost("Create")]
        public async Task<ApiResult> Create(string name)
        {
            bool b = await _iTypeInfoService.CreateAsync(new TypeInfo() { Name = name });
            if (!b) return ApiResultHelper.Error("添加失败");
            return ApiResultHelper.Success(b);
        }

        [HttpPost("Update")]
        public async Task<ApiResult> Update(int id, string name)
        {
            bool b = await _iTypeInfoService.EditAsync(new TypeInfo() { Id = id, Name = name });
            if (!b) return ApiResultHelper.Error("修改失败");
            return ApiResultHelper.Success(b);
        }

        [HttpPost("Delete")]
        public async Task<ApiResult> Delete(int id)
        {
            bool b = await _iTypeInfoService.DeleteAsync(id);
            if (!b) return ApiResultHelper.Error("删除失败");
            return ApiResultHelper.Success("删除成功");
        }
    }
}
